package pl.th.permission.plugin.node;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;

import java.util.List;

import pl.th.permission.plugin.ClassInjector;
import pl.th.permission.plugin.Utils;

public class PermissionClassNode extends ClassNode {

    private final ClassVisitor cv;

    public PermissionClassNode(ClassVisitor classVisitor) {
        super(Opcodes.ASM7);
        this.cv = classVisitor;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodNode method = new PermissionMethodNode(access, name, descriptor, signature, exceptions);
        methods.add(method);
        return method;
    }

    @Override
    public void visitEnd() {
        boolean find = false;
        for (MethodNode node : methods) {
            if (node instanceof PermissionMethodNode &&
                    ((PermissionMethodNode) node).getNeedAnnotation() != null) {
                find = true;
                break;
            }
        }
        if (find) {
            interfaces.add(Utils.getCallbackInterfaceName());
            ClassInjector classInjector = new ClassInjector(name, methods);
            classInjector.injectGrantMethodToClass(this);
            classInjector.injectDenyMethodToClass(this);
        }
        super.visitEnd();
        accept(cv);
    }


}
